<template>
  <div>
    <!-- 原有欢迎信息及展示部分保持不变... -->

    <!-- 新增轮播图管理卡片 -->
    <el-card style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span style="display: block; text-align: center;" class="system">轮播图管理</span>
        <el-upload
            class="avatar-uploader"
            action="http://47.97.65.149:9090/project/upload"
            :headers="{token: user.token}"
            :file-list="form.avatar?[form.avatar] :[]"
            list-type="picture"
            :on-success="handleUploadSuccess"
        >
          <el-button type="primary">上传新图片</el-button>
        </el-upload>
      </div>

      <el-row :gutter="20">
        <el-col
            v-for="(item, index) in imgList"
            :key="item.id"
            :span="6"
            style="margin-bottom: 20px;"
        >
          <el-card :body-style="{ padding: '0px' }">
            <img :src="item.imgurl" class="image" style="width: 100%; height: 200px; object-fit: cover;">
            <div style="padding: 14px;">
              <div class="bottom clearfix">
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteImage(item.id)"
                ></el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增竞赛管理卡片 -->
    <el-card style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span style="display: block; text-align: center;" class="system">竞赛管理</span>
        <el-button type="primary" @click="handleAddCompetition">新增竞赛</el-button>
      </div>


        <!-- 原有列保持不变... -->

          <div slot="header" class="clearfix">
            <span style="display: block; text-align: center;" class="system">竞赛信息</span>
          </div>
          <el-table
              :data="competitions"
              style="width: 100%"
              :row-style="{height: '60px'}"
          >
            <!-- 竞赛名称 -->
            <el-table-column prop="name" label="竞赛名称" width="200" align="center"/>
            <!-- 竞赛介绍 -->
            <el-table-column prop="intro" label="竞赛介绍" width="300" align="center"/>
            <!-- 报名时间 -->
            <el-table-column prop="signuptime" label="报名时间" width="150" align="center"/>
            <!-- 比赛时间 -->
            <el-table-column prop="competitionTime" label="比赛时间" width="150" align="center"/>
            <!-- 官网地址 -->
            <el-table-column label="官网地址" align="center">
              <template slot-scope="scope">
                <a
                    :href="scope.row.url"
                    target="_blank"
                    style="color: #409EFF; text-decoration: underline;"
                >
                  {{ scope.row.url }}
                </a>
              </template>
            </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 竞赛编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="30%"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="竞赛名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="竞赛介绍" prop="intro">
          <el-input type="textarea" v-model="form.intro"></el-input>
        </el-form-item>
        <el-form-item label="报名时间" prop="intro">
          <el-input  v-model="form.signuptime"></el-input>
        </el-form-item>
        <el-form-item label="比赛时间" prop="intro">
          <el-input  v-model="form.competitionTime"></el-input>
        </el-form-item>
        <el-form-item label="官网地址" prop="url">
          <el-input v-model="form.url"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Management",
  data() {
    return {
      // 原有数据保持不变...
      dialogVisible: false,
      dialogTitle: "新增竞赛",
      user:JSON.parse(localStorage.getItem('honey-user') ||('{}')),
      form: {
        id: "",
        name: "",
        intro: "",
        signuptime: '',
        competitionTime: '',
        url: ""
      },
      rules: {
        name: [{ required: true, message: "请输入竞赛名称", trigger: "blur" }],
        intro: [{ required: true, message: "请输入竞赛介绍", trigger: "blur" }],
        url: [{ required: true, message: "请输入官网地址", trigger: "blur" }]
      },
      competitions: [
      ],
      imgList: [],
      imgurls:''
    };
  },
  created(){
    this.load();
    this.load2();
  },
  methods: {
    // 原有方法保持不变...
    async load() {

      try {
        const response = await this.$request.get('/admin/selectImg');

        // 初始化班级数据，添加加载状态
        this.imgList = response.data

      } catch (error) {
        console.error('获取图片失败:', error);
      }
    }
    ,
    async load2() {

      try {
        const response = await this.$request.get('/admin/selectCompetitions');

        // 初始化班级数据，添加加载状态
        this.competitions = response.data

      } catch (error) {
        console.error('获取数据失败:', error);
      }
    }
    ,
    // 图片上传成功处理
    async handleUploadSuccess(response) {
      this.imgurls=response.data
      await this.load3(this.imgurls)
    },
    async load3(imgurls) {
      try {
        // 将URL包装成对象，匹配后端接收格式
        await this.$request.post('/admin/addimg',   imgurls );
        this.imgurls = '';
        this.$message.success("上传成功");
        this.load(); // 重新加载图片列表
      } catch (error) {
        console.error('保存图片失败:', error);
        this.$message.error("图片保存失败");
      }
    },
    // 删除图片
    async deleteImage(id) {
      try {
        await this.$confirm("确定删除该图片吗？", "提示", { type: "warning" });
        await this.$request.post(`/admin/deleteImg?id=${encodeURIComponent(id)}`);
        this.load()
        this.$message.success("删除成功");
      } catch (error) {
        console.error("删除失败:", error);
      }
    },

    // 新增竞赛
    handleAddCompetition() {
      this.form = {
        id: "",
        name: "",
        intro: "",
        signuptime: '',
        competitionTime: '',
        url: ""
      };
      this.dialogTitle = "新增竞赛";
      this.dialogVisible = true;
    },

    // 编辑竞赛
    handleEdit(index, row) {
      this.form = {
        ...row,

      };
      this.dialogTitle = "编辑竞赛";
      this.dialogVisible = true;
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.form.validate();

        const payload = {
          name: this.form.name,
          intro: this.form.intro,
          url: this.form.url,
          signuptime: this.form.signuptime,
          competitionTime: this.form.competitionTime
        };



        let url = '/admin/addCompetition';
        let method = 'post';

        if (this.form.id) {
          url = `/admin/updateCompetition?id=${this.form.id}`;
          method = 'post';
        }

        await this.$request[method](url, payload);
        this.$message.success("操作成功");
        this.dialogVisible = false;
        this.load2();
      } catch (error) {
        console.error("操作失败:", error);
        this.$message.error("操作失败，请检查数据");
      }
    },

    // 删除竞赛
    async handleDelete(index, row) {
      try {
        await this.$confirm("确定删除该竞赛吗？", "提示", { type: "warning" });
        await this.$request.post(`/admin/deleteCompetition?id=${encodeURIComponent(row.id)}`);
        this.competitions.splice(index, 1);
        this.$message.success("删除成功");
      } catch (error) {
        console.error("删除失败:", error);
      }
    }
  }
};
</script>

<style>
.upload-demo {
  margin-top: 10px;
  text-align: left;
}
</style>